package code.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Method extends Snippet {
	public static class Param {
		public Param() {
		}
		public Param(String type, String name) {
			this.name = name;
			this.type = type;
		}
		public String name;
		public String type;
		public int index;
		public boolean isConst;
	}

	public String returnType;
	public String paramsSource;
	public boolean isVirtual;
	public List<Param> params = new ArrayList<Method.Param>();

	@Override
	public List<Method> regularExpressionMatch(String source) {
		StringBuilder sb = new StringBuilder();
		sb.append("(virtual\\s+)?(\\w+)\\s+([a-z][a-z0-9_]*?)\\((.*?)\\)(.*?);"); // 0
		Pattern p = Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE
				| Pattern.DOTALL);
		Matcher m = p.matcher(source);
		List<Method> snippet = new ArrayList<Method>();
		while (m.find()) {
			System.out.println("_______________________");
			Method sp = new Method();
			sp.source = source;
			sp.snippet = m.group(0);
			sp.returnType = m.group(2);
			sp.name = m.group(3);
			sp.isVirtual = (m.group(1) != null&&m.group(1).contains("virtual"));
			sp.paramsSource = m.group(4) == null ? "" : m.group(4);
			sp.params = parseParams(sp.paramsSource);
			snippet.add(sp);

			System.out.println((sp.isVirtual?"abstract ":"")+sp.returnType + " " + sp.name + "("
					+ sp.paramsSource + ")");
			// System.out.println("snippet:"+sp.snippet);
			System.out.println("_______________________");
		}
		return snippet;
	}

	private List<Param> parseParams(String source) {
		if (source == null || source.equals("")) {
			return new ArrayList<Method.Param>();
		}
		StringBuilder sb = new StringBuilder();
		sb.append("(const\\s+)?([^\\s]+)\\s+([\\w]+)[,]?"); // 0
		Pattern p = Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE
				| Pattern.DOTALL);
		Matcher m = p.matcher(source);
		System.out.println("+++++++++");
		int i = 0;
		List<Param> params = new ArrayList<Method.Param>();
		while (m.find()) {
			Param param = new Param();
			param.index = i;
			param.isConst = m.group(1) != null;
			param.name = m.group(3);
			param.type = m.group(2);
			i++;
			System.out.print(" $" + param.index + "$"
					+ (param.isConst ? "final " : " ") + param.type + " "
					+ param.name);
			// System.out.println(m.group(2));
			// System.out.println(m.group(3));
			params.add(param);
		}
		System.out.println("\n+++++____++++");
		return params;

	}

}
